package com.javaweb.admin.entity;

/**
 * RateLimiter
 *
 * @author HanQuinn
 * Date: 2025/9/5
 * Time: 14:47
 */

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicLong;

public class RateLimiter {
    // 时间间隔：4小时（毫秒）
    public final long INTERVAL1DAY = 12 * 60 * 60 * 1000;
    public final long INTERVAL2DAYS = 2 * 12 * 60 * 60 * 1000;
    public final long INTERVAL4HOURS = 4 * 60 * 60 * 1000;
    public final long INTERVAL1HOURS = 1 * 60 * 60 * 1000;
    public final long INTERVAL10S = 10 * 1000;
    public final long INTERVAL30S = 30 * 1000;
    public final long INTERVAL1min = 60 * 1000;
    public final long INTERVAL30min = 30 * 60 * 1000;

    private final HashMap<String, AtomicLong> tasks = new HashMap<>();

    /**
     * 尝试执行接口调用（仅在上次调用超过12小时后执行）
     *
     * @param task 要执行的接口调用任务
     * @return true 表示已执行调用，false 表示忽略本次请求
     */
    public boolean tryInvoke(String taskKey, Runnable task, long interval) {
        if (!tasks.containsKey(taskKey)) {
            tasks.put(taskKey, new AtomicLong(0));
        }
        AtomicLong lastInvokeTime = tasks.get(taskKey);
        long currentTime = System.currentTimeMillis();
        long lastTime = lastInvokeTime.get();

        // 检查是否达到调用时间间隔
        if (currentTime - lastTime >= interval) {
            // 使用CAS操作确保线程安全
            if (lastInvokeTime.compareAndSet(lastTime, currentTime)) {
                task.run();  // 执行实际调用
                return true;
            }
        }
        return false;
    }
}